package org.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCommon {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final ObjectMapper objectMapper=new ObjectMapper(); // Spring Boot 自动配置的 Jackson 序列化器
    private static final Logger log = LoggerFactory.getLogger(RedisCommon.class);

    private static final long BEGIN_TIMESTAMP = 1704067200L;
    private static final int COUNT_BITS = 32;
    private static final Duration POP_TIMEOUT = Duration.ofSeconds(30);
    private static final int MAX_RETRY = 3;





    //存入有效时间的键值对
    public  <T> void setTemporaryCode(String key,T value,Integer timeout, TimeUnit timeUnit) throws JsonProcessingException {
        // 1. 根据类型处理数据
        if (value instanceof String) {
            // String 类型直接存储
            stringRedisTemplate.opsForValue().set(key, (String) value, timeout, timeUnit);
        } else {
            try {
                // 对象类型转为 JSON 存储
                String json = objectMapper.writeValueAsString(value);
                stringRedisTemplate.opsForValue().set(key, json, timeout, timeUnit);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Failed to serialize value to JSON", e);
            }
        }
    }
    //存入没有时间限制的键值对
    public  <T> void setPermanentCode(String key,T value) throws JsonProcessingException {
        if (value instanceof String) {
            stringRedisTemplate.opsForValue().set(key, (String) value);
        }
        else {
            try {
                String json = objectMapper.writeValueAsString(value);
                stringRedisTemplate.opsForValue().set(key, json);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Failed to serialize value to JSON", e);
            }
        }
    }
    //将object对象反序列并返回
    public  <T> T getValueByObject(String key,Class<T> type) throws JsonProcessingException {
        return objectMapper.readValue(stringRedisTemplate.opsForValue().get(key),type);
    }

    //获取String类型的值
    public String getValueOfString(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    //判断是否存在某个key
    public boolean checkHaveCode(String key){
        return stringRedisTemplate.hasKey(key);
    }

    //删除某个key
    public void deleteKey(String key){
        stringRedisTemplate.delete(key);
    }

    //尝试获取一个锁
    public boolean tryGetLock(String key,String value,Integer timeout){
        return stringRedisTemplate.opsForValue().setIfAbsent(key,value,timeout,TimeUnit.SECONDS);
    }
    //释放锁
    public void releaseLock(String key){
        String value =stringRedisTemplate.opsForValue().get(key);
        if(value.equals(key)){
            stringRedisTemplate.delete(key);
        }
    }

    //生成全局唯一id
    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2自增长
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        // 3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }
    //redis的消息队列存元素
    public <T> void addToMessageQueue(String key,T message) throws JsonProcessingException {
        try {
            String json = objectMapper.writeValueAsString(message);
            stringRedisTemplate.opsForList().leftPush(key, json);
        } catch (JsonProcessingException e) {
            log.error("消息序列化失败 key: {}, message: {}", key, message, e);
            throw new RuntimeException("消息序列化失败", e);
        }
    }

    //redis的消息队列取元素
    public <T> T getFromMessageQueue(String key, Class<T> clazz) throws JsonProcessingException {
            String json = null;
            try {
                // 开启额外的线程一直阻塞等待元素
                json = stringRedisTemplate.opsForList().rightPop(key, 0, TimeUnit.SECONDS);
                return objectMapper.readValue(json, clazz);
            } catch (JsonProcessingException e) {
                log.error("消息反序列化失败 key: {}, json: {}", key, json, e);
            }
            return null;
    }

    // 指数退避等待
    private void sleepBackoff(int attempt) {
        try {
            long sleepTime = (long) Math.pow(2, attempt) * 1000;
            Thread.sleep(Math.min(sleepTime, 10000)); // 最多10秒
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
        }
    }


}
